//
//  AutomationEditController.swift
//  home
//
//  Created by Yun Zeng on 2019/8/6.
//  Copyright © 2019 Yun Zeng. All rights reserved.
//

import UIKit

class AutomationEditController: UIViewController {
    var automation: HomeAutomation!
    @IBOutlet weak var navigationBar: UINavigationBar!
    @IBOutlet weak var navigationBarTitle: UINavigationItem!
    
    private lazy var enableLabel: AutomationEnableLabel = {
        let label = AutomationEnableLabel(frame: .zero)
        return label
    } ()
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        navigationBarTitle.title = self.automation.title
        self.view.backgroundColor = UIColor(hex: "EDEDED")
        
        let stackView = UIStackView()
        stackView.axis = .vertical
        stackView.distribution = .equalSpacing
        stackView.alignment = .leading
        stackView.translatesAutoresizingMaskIntoConstraints = false
        self.view.addSubview(stackView)
        stackView.topAnchor.constraint(equalTo: self.navigationBar.bottomAnchor, constant: 35).isActive = true
        stackView.leadingAnchor.constraint(equalTo: self.view.leadingAnchor, constant: 15).isActive = true
        stackView.trailingAnchor.constraint(equalTo: self.view.trailingAnchor, constant: -15).isActive = true
        
        stackView.addArrangedSubview(self.enableLabel)
        enableLabel.translatesAutoresizingMaskIntoConstraints = false
        enableLabel.topAnchor.constraint(equalTo: stackView.topAnchor).isActive = true
        enableLabel.leadingAnchor.constraint(equalTo: stackView.leadingAnchor).isActive = true
        enableLabel.trailingAnchor.constraint(equalTo: stackView.trailingAnchor).isActive = true
        enableLabel.heightAnchor.constraint(equalToConstant: 50).isActive = true
        
        stackView.addSpace(height: 15)
        
        let conditionLabel = UILabel()
        let attributes: [NSAttributedString.Key : Any] =
            [
                .font: UIFont.systemFont(ofSize: 24, weight: UIFont.Weight.medium),
                .kern: 0.45,
                .foregroundColor: UIColor(hex: "000000")
            ]
        let subattributes: [NSAttributedString.Key : Any] =
            [
                .font: UIFont.systemFont(ofSize: 16, weight: UIFont.Weight.regular),
                .kern: 0.45,
                .foregroundColor: UIColor(hex: "000000")
            ]
        conditionLabel.textAlignment = .left
        conditionLabel.autoresizingMask = .flexibleWidth
        conditionLabel.attributedText = NSAttributedString(string: "当:", attributes: attributes)
        
        stackView.addArrangedSubview(conditionLabel)
        conditionLabel.translatesAutoresizingMaskIntoConstraints = false
        conditionLabel.leadingAnchor.constraint(equalTo: stackView.leadingAnchor, constant: 3).isActive = true
        conditionLabel.heightAnchor.constraint(equalToConstant: 36).isActive = true
        
        stackView.addSpace(height: 5)
        
        let autoView = AutomationTriggerView(frame: .zero)
        autoView.icon = self.automation.icon
        autoView.title = self.automation.title
        autoView.subtitle = self.automation.getConditionDesc()
        autoView.backgroundColor = UIColor.white
        autoView.layer.cornerRadius = 12
        
        stackView.addArrangedSubview(autoView)
        autoView.translatesAutoresizingMaskIntoConstraints = false
        autoView.leadingAnchor.constraint(equalTo: stackView.leadingAnchor).isActive = true
        autoView.trailingAnchor.constraint(equalTo: stackView.trailingAnchor).isActive = true
        autoView.heightAnchor.constraint(equalToConstant: 68).isActive = true
        
        stackView.addSpace(height: 20)
        
        // 动作或者场景
        let actionsLabel = UILabel()
        actionsLabel.textAlignment = .left
        actionsLabel.autoresizingMask = .flexibleWidth
        stackView.addArrangedSubview(actionsLabel)
        actionsLabel.translatesAutoresizingMaskIntoConstraints = false
        actionsLabel.leadingAnchor.constraint(equalTo: stackView.leadingAnchor, constant: 3).isActive = true
        
        // 副标题
        let actionsDescLabel = UILabel()
        actionsDescLabel.textAlignment = .left
        actionsDescLabel.autoresizingMask = .flexibleWidth
        
        stackView.addSpace(height: 2)
        
        stackView.addArrangedSubview(actionsDescLabel)
        actionsDescLabel.translatesAutoresizingMaskIntoConstraints = false
        actionsDescLabel.leadingAnchor.constraint(equalTo: stackView.leadingAnchor, constant: 3).isActive = true
        
        actionsDescLabel.heightAnchor.constraint(equalToConstant: 30).isActive = true
        actionsLabel.heightAnchor.constraint(equalToConstant: 36).isActive = true
        
        // 关联场景
        if let sceneId = self.automation.scenes?.first,
           let scene =  HomeManager.instance.current!.sceneManager.getSceneById(id: sceneId) {
            
            stackView.addSpace(height: 8)
           
            let sceneView = SceneCellView(frame: .zero)
            sceneView.icon = scene.icon + "-on"
            sceneView.title = scene.name
            sceneView.state = .activated
            
            actionsLabel.attributedText = NSAttributedString(string: "场景:", attributes: attributes)
            actionsDescLabel.attributedText = NSAttributedString(string: "将执行以下场景", attributes: subattributes)
            stackView.addArrangedSubview(sceneView)
            
            sceneView.translatesAutoresizingMaskIntoConstraints = false
            sceneView.heightAnchor.constraint(equalToConstant: 60).isActive = true
            sceneView.widthAnchor.constraint(equalToConstant: 164).isActive = true
            sceneView.leadingAnchor.constraint(equalTo: stackView.leadingAnchor).isActive = true
        }
        
        // 关联动作
        else if let actions = self.automation.actions {
            let manager = ActionsServiceManager(actions: actions, home: HomeManager.instance.current!)
            let actionsView = ActionsCollectionView(frame: .zero, manager: manager)
            
            actionsLabel.attributedText = NSAttributedString(string: "配件:", attributes: attributes)
            actionsDescLabel.attributedText = NSAttributedString(string: "将执行以下动作", attributes: subattributes)
            
            view.addSubview(actionsView)
            stackView.addArrangedSubview(actionsView)
            actionsView.translatesAutoresizingMaskIntoConstraints = false
            actionsView.leadingAnchor.constraint(equalTo: stackView.leadingAnchor, constant: -17).isActive = true
            actionsView.trailingAnchor.constraint(equalTo: stackView.trailingAnchor, constant: 17).isActive = true
        }
        
        self.addEditMenu()
    }
    
    func addEditMenu() {
        let stackView = UIStackView()
        stackView.axis = .vertical
        stackView.distribution = .equalSpacing
        stackView.alignment = .center
        stackView.translatesAutoresizingMaskIntoConstraints = false
        self.view.addSubview(stackView)
        stackView.translatesAutoresizingMaskIntoConstraints = false
        stackView.topAnchor.constraint(equalTo: self.navigationBar.bottomAnchor, constant: 480).isActive = true
        stackView.leadingAnchor.constraint(equalTo: self.view.leadingAnchor, constant: 15).isActive = true
        stackView.trailingAnchor.constraint(equalTo: self.view.trailingAnchor, constant: -15).isActive = true
        stackView.customize(backgroundColor: UIColor.white, radiusSize: 10)
        
        let editBtn = UIButton()
        editBtn.setTitle("    添加或删除场景和配件", for: .normal)
        editBtn.contentHorizontalAlignment = .leading
        editBtn.setTitleColor(UIColor(red: 0, green: 122/255, blue: 255/255, alpha: 1), for: .normal)
        editBtn.setTitleColor(UIColor(red: 0, green: 122/255, blue: 255/255, alpha: 0.6), for: .highlighted)
        stackView.addCustomControl(view: editBtn, height: 48, pos: .top)
        
        let changeBtn = UIButton()
        changeBtn.setTitle("    测试此自动化", for: .normal)
        changeBtn.contentHorizontalAlignment = .leading
        changeBtn.setTitleColor(UIColor(red: 0, green: 122/255, blue: 255/255, alpha: 1), for: .normal)
        changeBtn.setTitleColor(UIColor(red: 0, green: 122/255, blue: 255/255, alpha: 0.6), for: .highlighted)
        stackView.addCustomControl(view: changeBtn, height: 48, pos: .bottom)
        
        let delBtn = UIButton()
        delBtn.setTitle("    删除自动化", for: .normal)
        delBtn.contentHorizontalAlignment = .leading
        delBtn.setTitleColor(UIColor(red: 1, green: 59/255, blue: 48/255, alpha: 1), for: .normal)
        delBtn.setTitleColor(UIColor(red: 1, green: 59/255, blue: 48/255, alpha: 0.6), for: .highlighted)
        
        self.view.addSubview(delBtn)

        delBtn.backgroundColor = UIColor.white
        delBtn.layer.cornerRadius = 10
        delBtn.translatesAutoresizingMaskIntoConstraints = false
        delBtn.leadingAnchor.constraint(equalTo: self.view.leadingAnchor, constant: 18).isActive = true
        delBtn.trailingAnchor.constraint(equalTo: self.view.trailingAnchor, constant: -18).isActive = true
        delBtn.topAnchor.constraint(equalTo: stackView.bottomAnchor, constant: 20).isActive = true
        delBtn.heightAnchor.constraint(equalToConstant: 48).isActive = true
    }
    
    
    @IBAction func save(_ sender: Any) {
        self.dismiss(animated: true)
    }
    
    @IBAction func cancel(_ sender: Any) {
        self.dismiss(animated: true)
    }
}

// MARK: - 自动化开关
class AutomationEnableLabel: UIView {
    
    private lazy var title: UILabel = {
        let label = UILabel()
        let attributes: [NSAttributedString.Key : Any] = [
        NSAttributedString.Key.font: UIFont.systemFont(ofSize: 17, weight: UIFont.Weight.regular),
        NSAttributedString.Key.kern: -0.41,
        NSAttributedString.Key.foregroundColor: UIColor.black]
        label.textAlignment = .left
        label.autoresizingMask = .flexibleWidth
        label.attributedText = NSAttributedString(string: "是否开启此自动化", attributes: attributes)
        return label
    } ()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        self.backgroundColor = UIColor(hex: "F2F2F2")
        self.heightAnchor.constraint(equalToConstant: 50).isActive = true
        self.layer.cornerRadius = 12
        self.backgroundColor = UIColor.white
        
        self.addSubview(self.title)
        title.translatesAutoresizingMaskIntoConstraints = false
        title.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 15).isActive = true
        title.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true
        
        let sw = UISwitch()
        self.addSubview(sw)
        sw.translatesAutoresizingMaskIntoConstraints = false
        sw.heightAnchor.constraint(equalToConstant: 32).isActive = true
        sw.trailingAnchor.constraint(equalTo: self.trailingAnchor, constant: -15).isActive = true
        sw.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true
        sw.isOn = true
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

// MARK: -自动化执行条件UIView
class AutomationTriggerView: UIView {
    
    var icon: String = "" {
        didSet {
            self.iconImage.image = UIImage(named: icon)
        }
    }
    
    var title: String = "" {
        didSet {
            self.titleLabel.attributedText = NSAttributedString(string: self.title, attributes: self.titleAttributes)
        }
    }
    
    var subtitle: String = "" {
        didSet {
            self.subtitleLabel.attributedText = NSAttributedString(string: self.subtitle, attributes: self.subtitleAttributes)
            titleCenterYAnchorConstraint.isActive = false
            if self.subtitle == "" {
                titleCenterYAnchorConstraint = titleLabel.centerYAnchor.constraint(equalTo: centerYAnchor)
            } else {
                titleCenterYAnchorConstraint = titleLabel.centerYAnchor.constraint(equalTo: centerYAnchor, constant: -10)
            }
            titleCenterYAnchorConstraint.isActive = true
        }
    }
    
    var titleCenterYAnchorConstraint: NSLayoutConstraint!
    
    private let titleAttributes: [NSAttributedString.Key : Any] =
        [
            .font: UIFont.systemFont(ofSize: 17, weight: UIFont.Weight.regular),
            .foregroundColor: UIColor(hex: "000000", alpha: 0.8),
            .kern: 0.32
        ]
    private let subtitleAttributes: [NSAttributedString.Key : Any] =
        [
            .font: UIFont.systemFont(ofSize: 14, weight: UIFont.Weight.regular),
            .foregroundColor: UIColor(hex: "000000", alpha: 0.5),
            .kern: 0.39
        ]
    
    private lazy var iconImage: UIImageView = {
        let view = UIImageView()
        return view
    } ()
    
    private lazy var titleLabel: UILabel = {
        let label = UILabel()
        return label
    } ()
    
    private lazy var subtitleLabel: UILabel = {
        let label = UILabel()
        return label
    } ()
    
    func initialize() {
        self.addSubview(self.iconImage)
        iconImage.translatesAutoresizingMaskIntoConstraints = false
        iconImage.leadingAnchor.constraint(equalTo: self.leadingAnchor, constant: 16).isActive = true
        iconImage.widthAnchor.constraint(equalToConstant: 40).isActive = true
        iconImage.heightAnchor.constraint(equalToConstant: 40).isActive = true
        iconImage.centerYAnchor.constraint(equalTo: self.centerYAnchor).isActive = true
        
        self.addSubview(self.titleLabel)
        titleLabel.translatesAutoresizingMaskIntoConstraints = false
        titleLabel.leadingAnchor.constraint(equalTo: iconImage.trailingAnchor, constant: 12).isActive = true
        titleCenterYAnchorConstraint = titleLabel.centerYAnchor.constraint(equalTo: centerYAnchor)
        titleCenterYAnchorConstraint.isActive = true
        titleLabel.heightAnchor.constraint(equalToConstant: 20).isActive = true
        titleLabel.autoresizingMask = .flexibleWidth
        
        self.addSubview(self.subtitleLabel)
        subtitleLabel.translatesAutoresizingMaskIntoConstraints = false
        subtitleLabel.leadingAnchor.constraint(equalTo: titleLabel.leadingAnchor).isActive = true
        subtitleLabel.heightAnchor.constraint(equalToConstant: 12).isActive = true
        subtitleLabel.centerYAnchor.constraint(equalTo: self.centerYAnchor, constant: 12).isActive = true
        subtitleLabel.autoresizingMask = .flexibleWidth
        
        // 详情图标
        let arrow = UIImageView(frame: .zero)
        self.addSubview(arrow)
        arrow.translatesAutoresizingMaskIntoConstraints = false
        arrow.heightAnchor.constraint(equalToConstant: 44).isActive = true
        arrow.widthAnchor.constraint(equalToConstant: 44).isActive = true
        arrow.centerYAnchor.constraint(equalTo: self.centerYAnchor).isActive = true
        arrow.trailingAnchor.constraint(equalTo: self.trailingAnchor, constant: -5).isActive = true
        arrow.image = UIImage(named: "panel-music-clock-detail-icon")
        
        self.backgroundColor = UIColor.white
    }
    
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        initialize()
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        initialize()
    }
}

// 获取自动化执行条件描述
// 初稿
extension HomeAutomation {
    func getConditionDesc() -> String {
        guard let conditions = self.conditions else  {
            return ""
        }
        if let condition = conditions.first {
            switch condition.condition {
            case .location(_):
                return "仅当我在家时"
            case .period(_):
                return ""
            case .characteristic(_):
                return ""
            default:
                break
            }
        }
        return ""
    }
}

